<script setup lang="ts">
import { ref, onBeforeUnmount, computed } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();

interface Props {
  item: {
    pid: string;
    images: string;
    headimg: string;
    title: string;
    price: number;
    oriprice: number;
    nickname: string;
  };
  itemWidth?: number;
}
const props = withDefaults(defineProps<Props>(), {
  item: () => ({
    pid: '',
    images: '',
    headimg: '',
    title: '',
    price: 0,
    oriprice: 0,
    nickname: '',
  }),
});

const imageUrl = computed(
  () => props.item.images + (props.itemWidth ? `?x-oss-process=image/resize,w_${props.itemWidth * 2},m_lfit` : '')
);

const isLoad = ref(true);

// 前往商品详情
const toDetail = (pid: string) => {
  router.push({
    path: '/hbMarket/productDetail',
    query: {
      pid,
    },
  });
};

onBeforeUnmount(() => {
  sessionStorage.removeItem('mainScrollTop');
});
</script>
<template>
  <div class="mb-3 rounded-lg van-haptics-feedback overflow-hidden bg-white" @click="toDetail(item.pid)">
    <div v-if="isLoad">
      <van-skeleton-image class="!w-full !h-[50vw]" />
      <div class="px-2 pb-2">
        <van-skeleton-paragraph class="!w-2/4 mt-1" />
        <van-skeleton-paragraph class="!w-1/4 mt-1" />
        <van-skeleton-paragraph class="!w-2/4 mt-1" />
      </div>
    </div>
    <div v-show="!isLoad">
      <van-image
        width="100%"
        height="50vw"
        fit="cover"
        :src="imageUrl"
        @load="isLoad = false"
        @error="isLoad = false"
      />
      <div class="px-2 pb-2">
        <div>{{ item.title }}</div>
        <div class="text-lg text-[#EC2D69] mt-1">
          {{ (item.price || 0).toFixed(1) }}
          <span class="text-xs">积分</span>
          <span class="text-xs line-through text-[#999999] ml-1">{{ (item.oriprice || 0).toFixed(1) }}</span>
        </div>
        <div class="mt-1 flex items-center">
          <van-image width="20px" height="20px" fit="cover" round :src="item.headimg" />
          <span class="text-xs text-[#666666] ml-2">{{ item.nickname }}</span>
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="less" scoped></style>
